<!--
 * @Description: iframe
-->
<template>
  <div id="zw-wrapper"  ref="zwWrapper">
    <iframe id="zwIframe" ref="zwIframe" :src="zwIframeUrl" :style="zwStyle" autoResize="true" ></iframe>
  </div>
</template>
<script>
  import { useTemplateStore } from '@/store/modules/template';
  import { mapActions, mapState, mapWritableState } from 'pinia';
  import emitter, {hiddenCap4TransparentMask, showCap4TransparentMask} from '@/plugins/global-callback';
  import globalMethods from '@/plugins/methods';
  import globalData, {BodyTypeEnums} from '@/plugins/data';
  import { useBaseInfoStore } from '@/store/modules/base-info';
  import Stateful from '@/layout/widgets/stateful'
  export default {
    name: 'ZwIframe',
    props: {
      autoHeight: {
        type: Boolean,
        default: true
      },
      scrollY: {
        type: Number,
        default: 0
      }
    },
    mixins: [Stateful],
    components: {
    },
    data: () => ({
      cache: '', //缓存一下表单发过来的数据
      zwStyle: {}, //正文样式
      isCap4: globalData.isCap4,
    }),
    computed: {
      ...mapWritableState(useTemplateStore, ['zwIframe', 'zwIframeUrl']),
      ...mapWritableState(useBaseInfoStore, ['showDealArea','isDataReady','baseInfo']),
    },
    created() {
      this.resize = globalMethods.debounce(() => {
        const [width, height] = this.cache.split('-');
        this.cache = '';
        this.setSize({ width, height });
      });
      this.registerEvent = null;
    },
    mounted() {
      window.bIsContentNewPage = true;
      //设置iframe对象
      this.zwIframe = this.$refs.zwIframe;
      //给自由协同详情提前设置上padding属性，方便计算高度
      if (globalData.bodyType === BodyTypeEnums.html.toString() && globalData.isSummary) {
        this.zwIframe.style.padding = '4px 20px 0px';
        // this.$refs.zwWrapper.style.padding = '4px 20px 0px';
      }
      //加载完毕
      emitter.subscribe('ContentLoaded', (obj)=>{
        this.setSize(obj);
        let officeTrance = this.zwIframe.contentWindow.document.getElementById('officeTransIframe');
        //没有转换。不显示原文档按钮
        if (!officeTrance){
          emitter.publish('hiddenBtn-event', 'viewSourceDoc');
        }
      });
      window.addEventListener('resize', this.resize);
    },
    beforeDestroy() {
      emitter.unsubscribe('ContentLoaded', this.setSize);
      window.removeEventListener('resize', this.resize);
    },
    watch:{
      scrollY(val){
        console.log('scrollY watched',val);
        if (this.baseInfo.zwIframe.isCap4){
          this.zwIframe.contentWindow.csdk.core.SDKAnchorMenuScrollEvent({top:val})
        }
      },
    },
    methods: {
      ...mapActions(useBaseInfoStore, ['toggleDealArea']),
      /**
       * @description: 根据表单返回的宽高，设置iframe容器的宽高。并标识为已准备好
       * @param {Number} width 表单宽
       * @param {Number} height 表单高
       */
      setSize({ width, height  }) {
        console.log('setSize window', width, height);
        const isSummary = globalData.isSummary;
        if (this.baseInfo.zwIframe.freeCol) {
          const mainbodyHtmlDiv = this.zwIframe.contentDocument.getElementById('mainbodyDiv');

          let nodeListOf = mainbodyHtmlDiv.querySelectorAll('p');
          for (let i = 0; i < nodeListOf.length; i++) {
            let item= nodeListOf[i];
            item.style.setProperty('word-wrap', 'break-word');
          }

          let contentHeight = mainbodyHtmlDiv.offsetHeight + 80;
          let scrollHeight = mainbodyHtmlDiv.scrollHeight;
          let clientHeight = this.$refs.zwWrapper.offsetParent.clientHeight -10;
          if (clientHeight > contentHeight) {
            contentHeight = clientHeight -30;
          }
          let forward = this.baseInfo.businessData.summary?.forwardMember||'';
          console.log('zm-height', scrollHeight, clientHeight, contentHeight);
          if (globalData.bodyType === BodyTypeEnums.html.toString()){
            //cap3标识
            let elementById = this.zwIframe.contentDocument.getElementById('attachmentAreaexcelImport');
            if (forward && elementById) {
              this.zwIframe.contentDocument.body.style.overflow = 'hidden'
              this.zwIframe.contentDocument.body.style.height = '100%'
              if (!this.cap3Load) {
                setTimeout(() => this.setSize({height, width}), 1000);
              }
              this.cap3Load = true
            }
            this.$refs.zwWrapper.style.minHeight = '100%';
            this.$refs.zwWrapper.style.height = '100%'
            this.$refs.zwWrapper.style.maxWidth = window.screen.width + 'px';
            if (isSummary) {
              this.zwStyle = {
                height: scrollHeight + 32  +'px',// 32 是回到顶部的高度
                backgroundColor: 'white',
                minWidth: '100%',
              };
              this.$nextTick(() => {
                this.zwIframe.style.width = mainbodyHtmlDiv.scrollWidth + 40 + 'px'; //图片可能显示不全
                //高度不足容器时候特殊处理
                let clientHeight = this.$refs.zwWrapper.offsetParent.clientHeight;
                let zwFrameHeight = this.zwIframe.clientHeight;
                if (clientHeight < zwFrameHeight) {
                  if (globalData.bodyType === BodyTypeEnums.html.toString() && isSummary && !this.htmlLoaded) {
                    this.setSize({width, height});
                    this.htmlLoaded = true;
                  }
                }
              })
            }
          }else {
            //流版签的
            $('#zw-wrapper').css({
              //正文的高度如果预先设置好，会导致里面编辑器高度坍缩
              height: '100%',
              minHeight: '100%',
              maxWidth: window.screen.width + 'px'
            });
            //流版签类型
            this.zwStyle = {
              height: (clientHeight)+'px',
            };
            //新建页面设置流版签的标识
            if (!isSummary){
              this.zwIframe?.OfficeAPI?.setOptions({"isSaveModifyMark":"false"});
            }
            
          }
        } else if (useBaseInfoStore().baseInfo.zwIframe.isCap4) {
          this.$refs.zwWrapper.style.minHeight='100%';
          
          //注册多正文页签切换事件
          if (!this.registerEvent) {
            this.zwIframe.contentWindow.contentAPI.registerEvent('changeViewEvent', (event) => {
              console.log('触发事件', event);
              const {currentIndex, index} = event;
              if (currentIndex !== index) {
                //触发事件隐藏处理区域
                this.toggleDealArea(index === 0);
              }
            });
            this.zwIframe.contentWindow.contentAPI.registerEvent('openProgressBar', (event) => {
              console.log('触发事件', event);
              showCap4TransparentMask();
            });
            this.zwIframe.contentWindow.contentAPI.registerEvent('closeProgressBar', (event) => {
              console.log('触发事件', event);
              hiddenCap4TransparentMask();
            });
            
            this.registerEvent = true;
            console.log('bind changeViewEvent');
          }
        }
        //标识为准备好了
        useTemplateStore().$patch((state) => {
          state.isIframeReady = true;
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
  #zw-wrapper {
    height: 100%;
    margin: 0 auto;
    transition: height $tn ease-in;

    > iframe {
      display: block;
      margin: 0 auto;
      width: 100%;
      height: 100%;
      min-height: 100%;
    }
  }
  /*低版本flex布局高度无法获取，用aaron.xiao提供方案，兼容class 识别处理*/
  .buggy-flex-h100{
    #zw-wrapper{
      position: absolute;
      width: 100%;
    }
  }
</style>
